import {
  Id,
  accessify,
  beType,
} from './entry'

import {
  Enum,
  Enumeral,
} from '../ast/types'

import sign, {
  isKeyword
} from '../ast/sign'

const
  OF        = sign.of,
  IGNORE    = sign['_'],
  IDENT     = sign.ident

function baseify (s) {
  let sign = s.soRight()
  if (sign === OF) return beType(s, s.beRight())
  s.beZero(sign)
  return null
}

export default function (s) {
  let
    start  = s.start,
    node   = new Enum(
      accessify(s.text()), s.beId(), baseify(s)
    ).start(start),
    sign = s.beNext(),
    names = []

  s.lead()

  while (sign) {
    let
      start  = s.beAlign().start,
      id = sign === IDENT && Id(s)
        || isKeyword(sign) && Id(s)
        || null,
      name = id && id.normalize() || '',
      ignore = !id && (sign === IGNORE || s.unexpected())
        || s.lowline(),
      val = null,
      end = s.end()

    if (name) {
      if (names.includes(name))
        s.exists('enumeration value of', id)
      names.push(name)
    }

    if (s.sps().colon())
      [val, sign] = beExpression(s, s.beRight())
    else
      sign = s.soMore()

    node.append(
      new Enumeral(id, ignore, val)
        .start(start).end(val && val.loc.end || end)
    )

    s.beZero(sign)
    sign = s.right()
  }

  return node.end(s.end)
}
